<template>
  <je-table
    ref="moreConfigRef"
    :stripe="false"
    resizable
    class="more-button-config-class"
    :height="tableHeight"
    border
    show-overflow
    auto-resize
    sync-resize
    keep-source
    show-header-overflow
    header-align="center"
    row-key
    :row-class-name="changeRowClassName"
    :store="gridStore"
    :edit-config="{
      trigger: 'click',
      mode: 'cell',
      showUpdateStatus: true,
      showStatus: false,
      activeMethod: isTableEdit,
    }"
    size="mini"
  >
    <je-table-column width="40">
      <template #header>
        <i
          style="font-size: 16px; cursor: pointer"
          class="fal fa-plus"
          @click="addColumnTable1"
        ></i>
      </template>
      <template #default="{ row }">
        <i
          style="font-size: 16px; cursor: pointer; margin-left: 5px; text-align: center"
          class="fal fa-times"
          @click="deleteColumnTable1(row)"
        ></i>
      </template>
    </je-table-column>
    <je-table-column
      title="按钮名"
      :edit-render="{ autofocus: '.ant-input' }"
      width="140"
      align="center"
      field="text"
    >
      <template #edit="{ row }">
        <je-input v-model:value="row.text" type="text"></je-input>
      </template>
    </je-table-column>
    <je-table-column
      title="编码"
      :edit-render="{ autofocus: '.ant-input' }"
      width="180"
      align="center"
      field="code"
    >
      <template #edit="{ row }">
        <je-input v-model:value="row.code" type="text"></je-input>
      </template>
    </je-table-column>
    <je-table-column title="图标" :edit-render="{}" width="180" align="center" field="icon">
      <template #edit="{ row }">
        <je-icon v-model:value="row.icon"></je-icon>
      </template>
    </je-table-column>
    <je-table-column title="方法" width="60" align="center">
      <template #default="{ row }">
        <span @click="addFunction(row)"
          ><i
            class="fas fa-bolt"
            :style="`cursor:pointer;color:${row.function ? '#F4CE4A' : '#8d98ab'} `"
          ></i
        ></span>
      </template>
    </je-table-column>
    <je-table-column
      title="显隐表达式"
      :edit-render="{ autofocus: '.ant-input' }"
      field="expression"
      min-width="180"
    >
      <template #edit="{ row }">
        <je-input v-model:value="row.expression">
          <template #suffix>
            <i
              class="setIcon fal fa-cog"
              @click="
                showExpress(
                  {
                    key: 'expression',
                    value: row.expression,
                  },
                  row,
                )
              "
            ></i>
          </template>
        </je-input>
      </template>
    </je-table-column>
    <je-table-column title="类型" :edit-render="{}" width="140" align="center">
      <template #default="{ row }">
        {{ getLabel(row.type, typeArr) }}
      </template>
      <template #edit="{ row }">
        <je-select v-model:value="row.type" type="value" :options="typeArr"></je-select>
      </template>
    </je-table-column>

    <je-table-column title="启用" width="60" align="center" field="enable" type="switch" />
    <je-table-column
      title="权限依赖按钮"
      :edit-render="{}"
      width="220"
      field="relyName"
      align="center"
    >
      <template #edit="{ row }">
        <je-grid-select
          v-model:value="row.relyName"
          name="relyName"
          config-info="JE_CORE_RESOURCEBUTTON,relyName~relyCode,RESOURCEBUTTON_NAME~RESOURCEBUTTON_CODE,S"
          :querys="querysArr"
          :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
        />
      </template>
    </je-table-column>
  </je-table>
</template>

<script>
  import { ref, defineComponent, onMounted } from 'vue';
  import { Grid, Icon, Modal, Input, Select, InputSelect, Data } from '@jecloud/ui';
  import { listenerEditorModal, ListenerExpressModal } from '@/helper/index.js';
  import { uniqueId } from '@jecloud/utils';
  import { useFuncStore } from '@/store/func-store';

  export default defineComponent({
    name: 'TreeConfigRef',
    components: {
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeInput: Input,
      JeIcon: Icon,
      JeSelect: Select,
      JeGridSelect: InputSelect.Grid,
    },
    props: {
      data: {
        type: Array,
        required: true,
      },
      funcCode: {
        type: String,
        required: true,
      },
    },
    emits: ['getMoreConfigRef'],
    setup(props, { emit }) {
      const querysArr = ref([
        { code: 'RESOURCEBUTTON_FUNCINFO_ID', value: props.funcCode, type: '=', cn: 'and' },
        { code: 'RESOURCEBUTTON_TYPE', value: ['GRID', 'ACTION'], type: 'in', cn: 'and' },
      ]);
      const moreConfigRef = ref(null);
      const gridStore = Data.Store.useGridStore({
        data: [],
      });
      const tableHeight = ref();
      const typeArr = [
        {
          value: 'button',
          text: '按钮',
          label: '按钮',
        },
        {
          value: 'divider',
          text: '分割线',
          label: '分割线',
        },
      ];
      // watch(
      //   () => testData.value,
      //   (val) => {
      //     if (val) {
      //       let length = val.length > 10 ? 10 : val.length;
      //       tableHeight.value = length ? 32 * (length + 1) : 200;
      //     }
      //   },
      //   { deep: true, immediate: true },
      // );
      const addColumnTable1 = async () => {
        // const newData = JSON.parse(JSON.stringify(testData.value));
        const record = {
          text: '',
          code: '',
          icon: '',
          function: '',
          expression: '',
          type: 'button',
          relyCode: '',
          relyname: '',
          enable: '1',
          systemField: '',
          id: uniqueId('grid_'),
        };
        // newData.push(record);
        // testData.value = newData;

        gridStore.insert(record, -1);

        methods.changeHeight();
      };
      const methods = {
        changeHeight() {
          const arr = gridStore.data;
          let length = arr.length > 10 ? 10 : arr.length;
          const height = length ? 32 * (length + 1) : 200;
          tableHeight.value = height <= 200 ? 200 : height;
        },
        isTableEdit({ row, column }) {
          if (
            row.type == 'divider' &&
            ['text', 'icon', 'expression', 'function', 'relyName', 'code'].includes(column.field)
          ) {
            return false;
          }
          return true;
        },
        // 类型为：分割线  时，整行背景色为灰色。
        changeRowClassName({ row }) {
          if (row.type == 'divider') {
            return 'scanBgColor';
          }
          return '';
        },
        getLabel(type, arr) {
          const items = arr.filter((item) => item.value == type) || [];
          return items && items[0] && items[0].text;
        },
        // 显隐藏表达式
        showExpress(obj, row) {
          obj.funcId = props.funcCode;
          ListenerExpressModal({
            ...obj,
            callback: (res) => {
              row[obj.key] = res.value;
            },
          });
        },
        // 在删除的时候，要记得，系统字段不允许删除
        deleteColumnTable1(record) {
          if (record.systemField) {
            Modal.alert('系统字段不允许删除', 'info');
            return false;
          }
          gridStore.remove(record);
          methods.changeHeight();
        },
        // 点击方法
        addFunction(row) {
          if (row.type == 'divider') {
            return false;
          }
          const funcStore = useFuncStore();
          listenerEditorModal({
            funcId: funcStore.funcBean.id,
            eventType: 'default',
            eventInfo: row.function,
            callback: (obj) => {
              Modal.message('保存成功', 'success');
              row.function = obj.eventInfo;
            },
          });
        },
      };
      onMounted(() => {
        gridStore.loadData(props.data);
        methods.changeHeight();
        emit('getMoreConfigRef', moreConfigRef.value);
      });
      return {
        ...methods,
        moreConfigRef,
        gridStore,
        addColumnTable1,
        typeArr,
        querysArr,
        tableHeight,
      };
    },
  });
</script>
<style lang="less">
  .more-button-config-class {
    .scanBgColor {
      background: #f5f5f5 !important; // 这边的颜色需要找产品要一下
      i {
        cursor: default !important;
      }
    }
    .ant-input-affix-wrapper {
      padding: 2px 15px !important;
    }
  }
</style>
